//
//  NRWCarMultipleChoiceVC.m
//  New_Runway
//
//  Created by NewLife on 2018/3/19.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWCarMultipleChoiceVC.h"
#import "NRWCarSelectTemplateModel.h"
#import "NRWCarAgeModel.h"
#import "NRWCarMileageModel.h"

@class NRWCarMultipleChoiceCell;

@protocol NRWCarMultipleChoiceCellDelegate<NSObject>

- (void)multipleChoiceCell:(NRWCarMultipleChoiceCell *)cell didClickWithIsSelect:(BOOL)isSelect index:(NSInteger)index;

@end

@interface NRWCarMultipleChoiceCell: UITableViewCell

@property (copy, nonatomic) NSString *titleStr;

@property (assign, nonatomic) BOOL didSelect;

@property (weak, nonatomic) id<NRWCarMultipleChoiceCellDelegate> delegate;

@end

@implementation NRWCarMultipleChoiceCell
{
    UILabel *titleLabel;
    UIImageView *imgView;
}

- (void)setTitleStr:(NSString *)titleStr {
    
    _titleStr = titleStr;
    
    titleLabel.text = titleStr;
}

- (void)setDidSelect:(BOOL)didSelect {
    
    _didSelect = didSelect;
    
    if (didSelect == YES) {
        imgView.image = getImageFromName(@"selected");
    } else {
        imgView.image = nil;
    }
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    
    titleLabel = DPLabel()
    .setFont(kPingFangRegular13())
    .setTextColor(getColorFromString(@"323232"))
    .setBackgroundColor([UIColor whiteColor]);
    
    imgView = DPImageView()
    .setBackgroundColor([UIColor whiteColor]);
    
    self.contentView.addSubview(titleLabel).addSubview(imgView);
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.contentView);
        make.left.equalTo(@16);
    }];
    
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView.mas_right).offset(-8);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.contentView addGestureRecognizer:tap];
}

- (void)tapAction:(UITapGestureRecognizer *)sender {
    
    if ([self.delegate respondsToSelector:@selector(multipleChoiceCell:didClickWithIsSelect:index:)]) {
        
        [self.delegate multipleChoiceCell:self didClickWithIsSelect:self.didSelect index:self.tag];
    }
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@interface NRWCarMultipleChoiceVC ()<UITableViewDataSource, UITableViewDelegate, NRWCarMultipleChoiceCellDelegate>

@end

@implementation NRWCarMultipleChoiceVC
{
    UITableView *tableView;
    NRWCarAgeModel *ageModel;
    NRWCarMileageModel *mileageModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
        
        self.navigationBarView.titleLabel.text = @"车龄区间";
        [self loadAgeListData];
    } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
        
        self.navigationBarView.titleLabel.text = @"里程区间";
        [self loadMileageListData];
    }
    
    [self.navigationBarView setupRightItemTitle:@"确定"];
    
    [self setupUI];
}

- (void)setupUI {
    
    tableView = DPTableViewForStyle(UITableViewStylePlain)
    .setDelegate(self)
    .setDataSource(self)
    .registerCell(NRWCarMultipleChoiceCell.class, @"cell")
    .setTableFooterView(DPView())
    .setFrame(CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH));
    
    tableView.allowsMultipleSelection = YES;
    
    self.view.addSubview(tableView);
}

- (void)rightItemClick {
    
    [self.navigationController safePopViewControllerWithClass:self.fromClass];
    
    if ([self.delegate respondsToSelector:@selector(multipleChoiceVC:ChoiceCompleted:)]) {
        
        NSMutableArray *arrM = [NSMutableArray array];
        
        if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
            
            for (NRWCarAgeListModel *itemModel in ageModel.result) {
                
                if ([self.selectAgeIdArr containsObject:itemModel.carAgeId]) {
                    
                    NRWCarSubAgeListModel *model = [[NRWCarSubAgeListModel alloc] init];
                    model.carAgeId = itemModel.carAgeId;
                    model.carAgeRemark = itemModel.carAgeRemark;
                    [arrM addObject:model];
                }
            }
            
            if ([self.delegate respondsToSelector:@selector(multipleChoiceVC:ChoiceCompleted:)]) {
                
                [self.delegate multipleChoiceVC:self ChoiceCompleted:arrM.copy];
            }
        } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
            
            for (NRWCarMileageListModel *itemModel in mileageModel.result) {
                
                if ([self.selectMileageIdArr containsObject:itemModel.carMileageId]) {
                    
                    NRWCarSubMileageListModel *model = [[NRWCarSubMileageListModel alloc] init];
                    model.carMileageId = itemModel.carMileageId;
                    model.carMileageRemark = itemModel.carMileageRemark;
                    [arrM addObject:model];
                }
            }
            
            if ([self.delegate respondsToSelector:@selector(multipleChoiceVC:ChoiceCompleted:)]) {
                
                [self.delegate multipleChoiceVC:self ChoiceCompleted:arrM.copy];
            }
        }
    }
}

- (void)loadAgeListData {
    
    [SVProgressHUD show];
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api, getCarAgeList] refreshRequest:NO cache:NO params:nil progressBlock:nil successBlock:^(id response) {
        
        [SVProgressHUD dismiss];
        
        ageModel = [NRWCarAgeModel mj_objectWithKeyValues:response];
        
        if ([response[@"code"] integerValue] == 1) {
            
            [tableView reloadData];
        } else {
            
            [SVProgressHUD showErrorWithStatus:ageModel.msg dismissDelay:1];
        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

- (void)loadMileageListData {
    
    [SVProgressHUD show];
    
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api, getCarMileageList] refreshRequest:NO cache:NO params:nil progressBlock:nil successBlock:^(id response) {
        
        [SVProgressHUD dismiss];
        
        mileageModel = [NRWCarMileageModel mj_objectWithKeyValues:response];
        
        if ([response[@"code"] integerValue] == 1) {
            
            [tableView reloadData];
        } else {
            
            [SVProgressHUD showErrorWithStatus:mileageModel.msg dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
        return ageModel.result.count;
    } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
        return mileageModel.result.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWCarMultipleChoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
        
        cell.titleStr = ageModel.result[indexPath.row].carAgeRemark;
        cell.didSelect = [self.selectAgeIdArr containsObject:ageModel.result[indexPath.row].carAgeId];
    } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
        
        cell.titleStr = mileageModel.result[indexPath.row].carMileageRemark;
        cell.didSelect = [self.selectMileageIdArr containsObject:mileageModel.result[indexPath.row].carMileageId];
    }
    cell.delegate = self;
    cell.tag = indexPath.row;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 40;
}

- (void)multipleChoiceCell:(NRWCarMultipleChoiceCell *)cell didClickWithIsSelect:(BOOL)isSelect index:(NSInteger)index {
    
    if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
        
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.selectAgeIdArr];
        
        if (isSelect == YES) {
            
            [arrM removeObject:ageModel.result[index].carAgeId];
        } else {
            
            [arrM addObject:ageModel.result[index].carAgeId];
        }
        
        self.selectAgeIdArr = arrM.copy;
    } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
        
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.selectMileageIdArr];
        
        if (isSelect == YES) {
            
            [arrM removeObject:mileageModel.result[index].carMileageId];
        } else {
            
            [arrM addObject:mileageModel.result[index].carMileageId];
        }
        
        self.selectMileageIdArr = arrM.copy;
    }
    
    [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

- (void)changeCellDidSelectStateWithIndexPath:(NSInteger)index didSelect:(BOOL)didSelect {

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    
    NRWCarMultipleChoiceCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    cell.didSelect = didSelect;

    if (self.type == NRWCarMultipleChoiceVCTypeAgeList) {
        ageModel.result[indexPath.row].didSelect = didSelect;
    } else if (self.type == NRWCarMultipleChoiceVCTypeMileageList) {
        mileageModel.result[indexPath.row].didSelect = didSelect;
    }
}


@end


